<?php


/* Local Functions */
/** 
 * Output the fields for a single player 
 */
function echoPlayer(& $player, $row, & $matchRecord, $pmr = false) {
    if (!$pmr) {
        $pmr = new PlayerMatchRecord($player, $matchRecord);
        $pmr->load();
    }
    $spps = $pmr->getSPPs();
    $skill = "&nbsp;";
    if ($pmr->hasSkill()) {
        $skill = $pmr->skill->name;
    }
    echo<<< EOQ
        $row
            <td class="sub">$player->link#$player->rosterNum $player->name $player->position</a></td>
            <td>$pmr->comps</td>
            <td>$pmr->tds</td>
            <td>$pmr->ints</td>
            <td>$pmr->cas</td>
            <td>$pmr->mvps</td>
            <td>$spps</td>
            <td>$skill</td>
            <td>$pmr->injury</td>
        </tr>
EOQ;
}

/**
 * Output the details of a whole team
 */
function echoTeamDetails(& $team, & $matchRecord) {
    $link = $team->getRosterLink();
    echo<<< EOQ
    <table border="0" cellspacing="0" cellpadding="2">
        <tr>
            <th colspan="9">$link</th>
        </tr>
        <tr>
            <th>Player</th>
            <th><span title="Completions">CP</span></th>
            <th><span title="Touchdowns">TD</span></th>
            <th><span title="Interceptions">IN</span></th>
            <th><span title="Casualties">CS</span></th>
            <th><span title="MVP">MVP</span></th>
            <th><span title="Star Player Points for the Game. This cannot be edited">SPPs</span></th>
            <th><span title="Skill gained during the game">Skill</span></th>
            <th><span title="Injury">Injury</span></th>
        </tr>
EOQ;
    // Players first
    $count = 0;
    $pmrDao = new PlayerMatchRecordDao();
    $pmrs = $pmrDao->getPMRsForMatch($matchRecord);
    foreach ($pmrs as $pmr) {
        $row = getEchoTR($count++);
        echoPlayer($pmr->player, $row, $matchRecord, $pmr);
    }
    $fanText = getFanText($matchRecord->fanFactor);
    $teamRRCost = 2 * $team->race->rerollCost;
    $rrCost = $matchRecord->rerolls * $teamRRCost;
    if ($rrCost <= 0)
        $rrCost = 0;
    $acCost = $matchRecord->coaches * 10;
    if ($acCost <= 0)
        $acCost = 0;
    $clCost = $matchRecord->cheerleaders * 10;
    if ($clCost <= 0)
        $clCost = 0;
    $apoCost = $matchRecord->apothecary * 50;
    if ($apoCost <= 0)
        $apoCost = 0;
    $totalCost = $rrCost + $acCost + $clCost + $apoCost;
    foreach ($matchRecord->getPurchases() as $mpp) {
        $totalCost += $mpp->cost;
    }

    echo<<< EOQ
		<tr>
			<th>Winnings</th>
			<th colspan="8">$matchRecord->winnings</th>
		</tr>
		<tr>
			<th>Fans</th>
			<th colspan="8">$fanText</th>
		</tr>
		<tr>
			<th colspan="9">Purchases \$$totalCost k</th>
		</tr>
EOQ;
    foreach ($matchRecord->getPurchases() as $mpp) {
        $pos = $mpp->position->position;
        echo<<< EOQ
		<tr>
			<td colspan="9">#$mpp->rosterNum $pos $mpp->name \$$mpp->cost k</td>
		</tr>
EOQ;
    }
    echo<<< EOQ
		<tr>
			<th colspan="4">Rerolls</th>
			<td colspan="5">$matchRecord->rerolls @$teamRRCost k = \$$rrCost k</td>
		</tr>
		<tr>
			<th colspan="4">Assistant Coaches</th>
			<td colspan="5">$matchRecord->coaches @10 k = \$$acCost k</td>
		</tr>
		<tr>
			<th colspan="4">Cheerleaders</th>
			<td colspan="5">$matchRecord->cheerleaders @10 k = \$$clCost k</td>
		</tr>
		<tr>
			<th colspan="4">Apothecary</th>
			<td colspan="5">$matchRecord->apothecary @50 k = \$$apoCost k</td>
		</tr>
    </table>
EOQ;
}

function echoApproval($approval, $lastApproval = false) {
    if ($approval and $approval->canApprove()) {
        $val = "Approve";
        if ($lastApproval) {
            $val = "Approve and Update Teams";
        }
        echo<<< EOQ
<form method="post">
<input type="hidden" name="appid" value="$approval->id">
<input type="submit" name="approve" value="$val" alt="Approve for $approval->approvalType">
</form>
EOQ;
    } else
        if ($approval) {
            if ($approval->isApproved()) {
                $type = ucfirst($approval->approvalType);
                $coach = loadCoach($approval->actualCoachId);
                echo<<< EOQ
$type approved by $coach->name on $approval->timestamp
EOQ;
            } else {
                $coach = loadCoach($approval->expectedCoachId);
                echo<<< EOQ
Needs $approval->approvalType approval by $coach->name 
EOQ;
            }
        } else {
            echo "&nbsp;";
        }
}

/* Start of Page */
include_once ("includes/init.php");
include_once ("includes/match_utils.php");

/* Requires match Id of match to be updated */
$matchId = getParam("matchId");
if (!isset ($matchId)) {
    $redirect = "results.php";
    $redirectStr = "Match Submission";
    $message = "Unable to identify match to update details of";
    include ("includes/redirect.php");
    return;
}

$match = $matches->getMatch($matchId);
$homeTeam = $teams->getTeam($match->homeRec->teamId);
$awayTeam = $teams->getTeam($match->awayRec->teamId);
$ad = new ApprovalDao();
$approvals = $ad->findMatchApprovals($match);
$canEdit = false;
if (isset ($loggedin)) {
    $canEdit = $loggedin->canEditMatch($match);
}

$submit = getParam("submit");
$mrid = getParam("mrid");
$comments = getParam("comments");
if (isset ($submit)) {
    if ($match->homeRec->id == $mrid && $loggedin->canEditComment($match->homeRec)) {
        $match->homeRec->comments = stripslashes($comments);
        $match->homeRec->update();
    } else
        if ($match->awayRec->id == $mrid && $loggedin->canEditComment($match->awayRec)) {
            $match->awayRec->comments = stripslashes($comments);
            $match->awayRec->update();
        }
    $matches->updateMatch($match);
}

$approve = getParam("approve");
$appid = getParam("appid");
if (isset ($approve)) {
    $approval = $approvals[$appid];
    if (isset ($approval)) {
        $approval->approve();
        if (!$match->teamsUpdated && $ad->isLastApproval($approval)) {
            $updater = new MatchUpdater();
            $errors = $updater->updateTeams($match, $homeTeam, $awayTeam);
            $md = new MatchDao();
            $md->update($match, false);
            if (0 == count(($errors))) {
                $ad->save($approval);
                $redirect = "match_view.php?matchId=$matchId&reload=true";
                $redirectStr = "Updating";
                $message = "Updating the match";
                include ("includes/redirect.php");
                return;
            }
        } else {
            $ad->save($approval);
        }
        $approvals = $ad->findMatchApprovals($match);
    }
}

/* Main Page */
$title = $homeTeam->name . " vs " . $awayTeam->name;
include_once ("includes/header.php");
echo<<< EOQ
    <caption><h1>Match Details</h1></caption>
EOQ;
if ($canEdit) {
    echo<<< EOQ
	<tr>
		<td colspan="2" align="right"><a href="match_edit.php?matchId=$match->id">Edit</a></td>
    </tr>
EOQ;
}
if (isset ($errors) && count($errors) > 0) {
    foreach ($errors as $error) {
        echo<<< EOQ
	<tr>
		<td colspan="2" align="center"><div class="red">Error: $error</div></td>
    </tr>
EOQ;
    }
}
echo<<< EOQ
    <tr><td colspan="2"><table width="100%" cellspacing="0" cellpadding="2">
<tr>
  <th align="center" rowSpan="2" class="strong">Date</th>
  <th align="center" rowSpan="2" class="strong">Home</th>
  <th align="center" colspan="2" class="strong">Touch&nbsp;Downs</th>
  <th align="center" rowSpan="2" class="strong">Away</th>
  <th align="center" rowSpan="2" class="strong">Gate</th>
  <th align="center" rowSpan="2" class="strong">&nbsp;</th>
</tr>
<tr>
  <td align="center" colspan="2" class="small">Casualties</td>
</tr>
EOQ;
$rowcount = 1;
echo getEchoTR(++ $rowcount);
echo "<th align=center rowSpan=2>" . getEchoValue($match->datePlayed) . "</th>\n";
echo "<td align=center rowSpan=2><b>" . getEchoValue($homeTeam->getRosterLink()) . "<br />(" . getEchoValue($homeTeam->coach->getName()) . ")</b></td>";
echo "<th align=center>" . getEchoValue($match->homeRec->score) . "</th>";
echo "<th align=center>" . getEchoValue($match->awayRec->score) . "</th>";
echo "<td align=center rowSpan=2><b>" . getEchoValue($awayTeam->getRosterLink()) . "<br />(" . getEchoValue($awayTeam->coach->getName()) . ")</b></td>";
echo "<td align=center>" . getEchoValue($match->type) . "</td>";
echo "</tr>\n";
echo getEchoTR($rowcount);
echo "<td align=right><font size=-1>" . getEchoValue($match->homeRec->casualties) . "</font></td>";
echo "<td align=left><font size=-1>" . getEchoValue($match->awayRec->casualties) . "</font></td>";
echo "<td align=center>" . getEchoValue($match->gate) . "</td>";
echo "</td></tr>\n";

showComments($rowcount, $match->homeRec->comments, $homeTeam->coach, $match->awayRec->comments, $awayTeam->coach, $match->id);
echo getEchoTR($rowcount);
echo "<td colspan=6>&nbsp;</td></tr>";
echo<<< EOQ
	</table></td></tr>
    <tr>
        <td valign="top">
        <!-- Home Team Details -->
EOQ;
echoTeamDetails($homeTeam, $match->homeRec);
echo<<< EOQ
        </td>
        <td valign="top">
        <!-- Away Team Details -->
EOQ;
echoTeamDetails($awayTeam, $match->awayRec);
echo<<< EOQ
        </td>
    </tr>
EOQ;
if (count($approvals) > 0) {
    $homeApp = false;
    $awayApp = false;
    $commApp = false;
    foreach ($approvals as $approval) {
        if ($approval->isHome()) {
            $homeApp = $approval;
        } else
            if ($approval->isAway()) {
                $awayApp = $approval;
            } else {
                $commApp = $approval;
            }
    }
    if ($homeApp) {
        echo "<tr><td align=\"center\">";
        echoApproval($homeApp, !$match->teamsUpdated && $ad->isLastApproval($homeApp));
    }
    if ($awayApp) {
        echo "</td><td align=\"center\">";
        echoApproval($awayApp, !$match->teamsUpdated && $ad->isLastApproval($awayApp));
    }
    if ($commApp) {
        echo "</td></tr><tr><td colspan=\"2\" align=\"center\">";
        echoApproval($commApp, !$match->teamsUpdated && $ad->isLastApproval($commApp));
    }
    echo "</td></tr>";
}
?>

